package com.upu173.qrcode.core;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;

import com.andbase.library.utils.AbLogUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.util.Hashtable;

public class DecodeUtil {


    public static  String  decode(Bitmap bitmap) {
        try {
            Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);

            int[] bitmapData = new int[bitmap.getWidth() * bitmap.getHeight()];
            bitmap.getPixels(bitmapData, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

            RGBLuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(),bitmapData);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader qrCodeReader = new QRCodeReader();
            Result result = qrCodeReader.decode(binaryBitmap, hints);
            String code = result.getText();
            AbLogUtil.e("DecodeThread", "扫描到了二维码：" + code);
            return  code;
        } catch (Exception e) {
            e.printStackTrace();
            AbLogUtil.e("DecodeThread", "扫描二维码异常：" + e.getMessage());
        }
        return  "";
    }

    public static String decode(byte[] yuvData, int width, int height, Rect frameRect) {

        try {
            Log.e("DecodeThread", "开始识别二维码...");
            Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
            //hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
            PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(yuvData,
                    width,
                    height,
                    (width-frameRect.height())/2,(height - frameRect.width())/2
                    ,frameRect.height(),
                    frameRect.width(),
                    false);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader qrCodeReader = new QRCodeReader();
            Result result = qrCodeReader.decode(binaryBitmap, hints);
            String code = result.getText();
            AbLogUtil.e("DecodeThread","扫描到了二维码：" + code);
            return  code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "";

    }
}
